home *** CD-ROM | disk | FTP | other *** search
/ Graphics Plus / Graphics Plus.iso / amiga / plotting / gnuplot3.lzh / gnuplot / contour.c < prev    next >
C/C++ Source or Header  |  1991-07-18  |  41KB  |  1,237 lines

  1. /* GNUPLOT - contour.c */
  2. /*
  3.  * Copyright (C) 1986, 1987, 1990, 1991   Thomas Williams, Colin Kelley
  4.  *
  5.  * Permission to use, copy, and distribute this software and its
  6.  * documentation for any purpose with or without fee is hereby granted, 
  7.  * provided that the above copyright notice appear in all copies and 
  8.  * that both that copyright notice and this permission notice appear 
  9.  * in supporting documentation.
  10.  *
  11.  * Permission to modify the software is granted, but not the right to
  12.  * distribute the modified code.  Modifications are to be distributed 
  13.  * as patches to released version.
  14.  *  
  15.  * This software is provided "as is" without express or implied warranty.
  16.  * 
  17.  *
  18.  * AUTHORS
  19.  * 
  20.  *   Original Software:
  21.  *       Gershon Elber
  22.  * 
  23.  * Send your comments or suggestions to 
  24.  *  pixar!info-gnuplot@sun.com.
  25.  * This is a mailing list; to join it send a note to 
  26.  *  pixar!info-gnuplot-request@sun.com.  
  27.  * Send bug reports to
  28.  *  pixar!bug-gnuplot@sun.com.
  29.  */
  30.  
  31. #include <stdio.h>
  32. #include "plot.h"
  33.  
  34. #define DEFAULT_NUM_OF_ZLEVELS  10  /* Some dflt values (setable via flags). */
  35. #define DEFAULT_NUM_APPROX_PTS  5
  36. #define DEFAULT_BSPLINE_ORDER  3
  37. #define MAX_NUM_OF_ZLEVELS      100 /* Some max. values (setable via flags). */
  38. #define MAX_NUM_APPROX_PTS      100
  39. #define MAX_BSPLINE_ORDER      10
  40.  
  41. #define INTERP_NOTHING   0            /* Kind of interpolations on contours. */
  42. #define INTERP_CUBIC     1                           /* Cubic spline interp. */
  43. #define APPROX_BSPLINE   2                         /* Bspline interpolation. */
  44.  
  45. #define ACTIVE   1                    /* Status of edges at certain Z level. */
  46. #define INACTIVE 2
  47.  
  48. #define OPEN_CONTOUR     1                                 /* Contour kinds. */
  49. #define CLOSED_CONTOUR   2
  50.  
  51. #define EPSILON  1e-5              /* Used to decide if two float are equal. */
  52. #define INFINITY 1e10
  53.  
  54. #ifndef TRUE
  55. #define TRUE     -1
  56. #define FALSE    0
  57. #endif
  58.  
  59. #define DEFAULT_NUM_CONTOURS    10
  60. #define MAX_POINTS_PER_CNTR     100
  61. #define SHIFT_Z_EPSILON        0.000301060 /* Dec. change of poly bndry hit.*/
  62.  
  63. #define abs(x)  ((x) > 0 ? (x) : (-(x)))
  64. #define sqr(x)  ((x) * (x))
  65.  
  66. typedef double tri_diag[3];         /* Used to allocate the tri-diag matrix. */
  67. typedef double table_entry[4];           /* Cubic spline interpolation 4 coef. */
  68.  
  69. struct vrtx_struct {
  70.     double X, Y, Z;                       /* The coordinates of this vertex. */
  71.     struct vrtx_struct *next;                             /* To chain lists. */
  72. };
  73.  
  74. struct edge_struct {
  75.     struct poly_struct *poly[2];   /* Each edge belongs to up to 2 polygons. */
  76.     struct vrtx_struct *vertex[2]; /* The two extreme points of this vertex. */
  77.     struct edge_struct *next;                             /* To chain lists. */
  78.     int status, /* Status flag to mark edges in scanning at certain Z level. */
  79.     boundary;                   /* True if this edge is on the boundary. */
  80. };
  81.  
  82. struct poly_struct {
  83.     struct edge_struct *edge[3];           /* As we do triangolation here... */
  84.     struct poly_struct *next;                             /* To chain lists. */
  85. };
  86.  
  87. struct cntr_struct {           /* Contours are saved using this struct list. */
  88.     double X, Y;                          /* The coordinates of this vertex. */
  89.     struct cntr_struct *next;                             /* To chain lists. */
  90. };
  91.  
  92. static int test_boundary;    /* If TRUE look for contours on boundary first. */
  93. static struct gnuplot_contours *contour_list = NULL;
  94. static double crnt_cntr[MAX_POINTS_PER_CNTR * 2];
  95. static int crnt_cntr_pt_index = 0;
  96. static double contour_level = 0.0;
  97. static table_entry *hermit_table = NULL;    /* Hold hermite table constants. */
  98. static int num_of_z_levels = DEFAULT_NUM_OF_ZLEVELS;  /* # Z contour levels. */
  99. static int num_approx_pts = DEFAULT_NUM_APPROX_PTS;/* # pts per approx/inter.*/
  100. static int bspline_order = DEFAULT_BSPLINE_ORDER;   /* Bspline order to use. */
  101. static int interp_kind = INTERP_NOTHING;  /* Linear, Cubic interp., Bspline. */
  102.  
  103. static void gen_contours();
  104. static int update_all_edges();
  105. static struct cntr_struct *gen_one_contour();
  106. static struct cntr_struct *trace_contour();
  107. static struct cntr_struct *update_cntr_pt();
  108. static int fuzzy_equal();
  109. static void gen_triangle();
  110. static struct vrtx_struct *gen_vertices();
  111. static struct edge_struct *gen_edges_middle();
  112. static struct edge_struct *gen_edges();
  113. static struct poly_struct *gen_polys();
  114. static void free_contour();
  115. static void put_contour();
  116. static put_contour_nothing();
  117. static put_contour_cubic();
  118. static put_contour_bspline();
  119. static calc_tangent();
  120. static int count_contour();
  121. static complete_spline_interp();
  122. static calc_hermit_table();
  123. static hermit_interp();
  124. static prepare_spline_interp();
  125. static int solve_tri_diag();
  126. static gen_bspline_approx();
  127. static double fetch_knot();
  128. static eval_bspline();
  129.  
  130. /*
  131.  * Entry routine to this whole set of contouring module.
  132.  */
  133. struct gnuplot_contours *contour(num_isolines, iso_lines,
  134.                  ZLevels, approx_pts, kind, order1)
  135. int num_isolines;
  136. struct iso_curve *iso_lines;
  137. int ZLevels, approx_pts, kind, order1;
  138. {
  139.     int i;
  140.     struct poly_struct *p_polys, *p_poly;
  141.     struct edge_struct *p_edges, *p_edge;
  142.     struct vrtx_struct *p_vrts, *p_vrtx;
  143.     double x_min, y_min, z_min, x_max, y_max, z_max, z, dz, z_scale = 1.0;
  144.  
  145.     num_of_z_levels = ZLevels;
  146.     num_approx_pts = approx_pts;
  147.     bspline_order = order1 - 1;
  148.     interp_kind = kind;
  149.  
  150.     contour_list = NULL;
  151.  
  152.     if (interp_kind == INTERP_CUBIC) calc_hermit_table();
  153.  
  154.     gen_triangle(num_isolines, iso_lines, &p_polys, &p_edges, &p_vrts,
  155.         &x_min, &y_min, &z_min, &x_max, &y_max, &z_max);
  156.     dz = (z_max - z_min) / (num_of_z_levels+1);
  157.     /* Step from z_min+dz upto z_max-dz in num_of_z_levels times. */
  158.     z = z_min + dz;
  159.     crnt_cntr_pt_index = 0;
  160.  
  161.     for (i=0; i<num_of_z_levels; i++, z += dz) {
  162.     contour_level = z;
  163.     gen_contours(p_edges, z + dz * SHIFT_Z_EPSILON, x_min, x_max,
  164.                             y_min, y_max);
  165.     }
  166.  
  167.     /* Free all contouring related temporary data. */
  168.     while (p_polys) {
  169.     p_poly = p_polys -> next;
  170.     free (p_polys);
  171.     p_polys = p_poly;
  172.     }
  173.     while (p_edges) {
  174.     p_edge = p_edges -> next;
  175.     free (p_edges);
  176.     p_edges = p_edge;
  177.     }
  178.     while (p_vrts) {
  179.     p_vrtx = p_vrts -> next;
  180.     free (p_vrts);
  181.     p_vrts = p_vrtx;
  182.     }
  183.  
  184.     if (interp_kind == INTERP_CUBIC) free(hermit_table);
  185.  
  186.     return contour_list;
  187. }
  188.  
  189. /*
  190.  * Adds another point to the currently build contour.
  191.  */
  192. add_cntr_point(x, y)
  193. double x, y;
  194. {
  195.     int index;
  196.  
  197.     if (crnt_cntr_pt_index >= MAX_POINTS_PER_CNTR-1) {
  198.     index = crnt_cntr_pt_index - 1;
  199.     end_crnt_cntr();
  200.     crnt_cntr[0] = crnt_cntr[index * 2];
  201.     crnt_cntr[1] = crnt_cntr[index * 2 + 1];
  202.     crnt_cntr_pt_index = 1; /* Keep the last point as first of this one. */
  203.     }
  204.     crnt_cntr[crnt_cntr_pt_index * 2] = x;
  205.     crnt_cntr[crnt_cntr_pt_index * 2 + 1] = y;
  206.     crnt_cntr_pt_index++;
  207. }
  208.  
  209. /*
  210.  * Done with current contour - create gnuplot data structure for it.
  211.  */
  212. end_crnt_cntr()
  213. {
  214.     int i;
  215.     struct gnuplot_contours *cntr = (struct gnuplot_contours *)
  216.                     alloc(sizeof(struct gnuplot_contours),
  217.                           "gnuplot_contour");
  218.  
  219.     cntr->coords = (struct coordinate *) alloc(sizeof(struct coordinate) *
  220.                               crnt_cntr_pt_index,
  221.                            "contour coords");
  222.     for (i=0; i<crnt_cntr_pt_index; i++) {
  223.     cntr->coords[i].x = crnt_cntr[i * 2];
  224.     cntr->coords[i].y = crnt_cntr[i * 2 + 1];
  225.     cntr->coords[i].z = contour_level;
  226.     }
  227.     cntr->num_pts = crnt_cntr_pt_index;
  228.  
  229.     cntr->next = contour_list;
  230.     contour_list = cntr;
  231.  
  232.     crnt_cntr_pt_index = 0;
  233. }
  234.  
  235. /*
  236.  * Generates all contours by tracing the intersecting triangles.
  237.  */
  238. static void gen_contours(p_edges, z_level, x_min, x_max, y_min, y_max)
  239. struct edge_struct *p_edges;
  240. double z_level, x_min, x_max, y_min, y_max;
  241. {
  242.     int num_active,                        /* Number of edges marked ACTIVE. */
  243.     contour_kind;                /* One of OPEN_CONTOUR, CLOSED_CONTOUR. */
  244.     struct cntr_struct *p_cntr;
  245.  
  246.     num_active = update_all_edges(p_edges, z_level);           /* Do pass 1. */
  247.  
  248.     test_boundary = TRUE;        /* Start to look for contour on boundaries. */
  249.  
  250.     while (num_active > 0) {                                   /* Do Pass 2. */
  251.         /* Generate One contour (and update MumActive as needed): */
  252.     p_cntr = gen_one_contour(p_edges, z_level, &contour_kind, &num_active);
  253.     put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max,
  254.                   contour_kind); /* Emit it in requested format. */
  255.     }
  256. }
  257.  
  258. /*
  259.  * Does pass 1, or marks the edges which are active (crosses this z_level)
  260.  * as ACTIVE, and the others as INACTIVE:
  261.  * Returns number of active edges (marked ACTIVE).
  262.  */
  263. static int update_all_edges(p_edges, z_level)
  264. struct edge_struct *p_edges;
  265. double z_level;
  266. {
  267.     int count = 0;
  268.  
  269.     while (p_edges) {
  270.     if (((p_edges -> vertex[0] -> Z >= z_level) &&
  271.          (p_edges -> vertex[1] -> Z <= z_level)) ||
  272.         ((p_edges -> vertex[1] -> Z >= z_level) &&
  273.          (p_edges -> vertex[0] -> Z <= z_level))) {
  274.         p_edges -> status = ACTIVE;
  275.         count++;
  276.     }
  277.     else p_edges -> status = INACTIVE;
  278.     p_edges = p_edges -> next;
  279.     }
  280.  
  281.     return count;
  282. }
  283.  
  284. /*
  285.  * Does pass 2, or find one complete contour out of the triangolation data base:
  286.  * Returns a pointer to the contour (as linked list), contour_kind is set to
  287.  * one of OPEN_CONTOUR, CLOSED_CONTOUR, and num_active is updated.
  288.  */
  289. static struct cntr_struct *gen_one_contour(p_edges, z_level, contour_kind,
  290.                                 num_active)
  291. struct edge_struct *p_edges;
  292. double z_level;
  293. int *contour_kind, *num_active;
  294. {
  295.     struct edge_struct *pe_temp;
  296.  
  297.     if (test_boundary) {    /* Look for something to start with on boundary: */
  298.     pe_temp = p_edges;
  299.     while (pe_temp) {
  300.         if ((pe_temp -> status == ACTIVE) && (pe_temp -> boundary)) break;
  301.         pe_temp = pe_temp -> next;
  302.     }
  303.     if (!pe_temp) test_boundary = FALSE;/* No more contours on boundary. */
  304.     else {
  305.         *contour_kind = OPEN_CONTOUR;
  306.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  307.     }
  308.     }
  309.  
  310.     if (!test_boundary) {        /* Look for something to start with inside: */
  311.     pe_temp = p_edges;
  312.     while (pe_temp) {
  313.         if ((pe_temp -> status == ACTIVE) && (!(pe_temp -> boundary)))
  314.         break;
  315.         pe_temp = pe_temp -> next;
  316.     }
  317.     if (!pe_temp) {
  318.         *num_active = 0;
  319.         return NULL;
  320.     }
  321.     else {
  322.         *contour_kind = CLOSED_CONTOUR;
  323.         return trace_contour(pe_temp, z_level, num_active, *contour_kind);
  324.     }
  325.     }
  326.     return NULL;             /* We should never be here, but lint... */
  327. }
  328.  
  329. /*
  330.  * Search the data base along a contour starts at the edge pe_start until
  331.  * a boundary edge is detected or until we close the loop back to pe_start.
  332.  * Returns a linked list of all the points on the contour
  333.  * Also decreases num_active by the number of points on contour.
  334.  */
  335. static struct cntr_struct *trace_contour(pe_start, z_level, num_active,
  336.                                 contour_kind)
  337. struct edge_struct *pe_start;
  338. double z_level;
  339. int *num_active, contour_kind;
  340. {
  341.     int i, in_middle;       /* If TRUE the z_level is in the middle of edge. */
  342.     struct cntr_struct *p_cntr, *pc_tail;
  343.     struct edge_struct *p_edge = pe_start, *p_next_edge;
  344.     struct poly_struct *p_poly, *PLastpoly = NULL;
  345.  
  346.     /* Generate the header of the contour - the point on pe_start. */
  347.     if (contour_kind == OPEN_CONTOUR) pe_start -> status = INACTIVE;
  348.     (*num_active)--;
  349.     p_cntr = pc_tail = update_cntr_pt(pe_start, z_level, &in_middle);
  350.     if (!in_middle) {
  351.     return NULL;
  352.     }
  353.  
  354.     do {
  355.     /* Find polygon to continue (Not where we came from - PLastpoly): */
  356.     if (p_edge -> poly[0] == PLastpoly) p_poly = p_edge -> poly[1];
  357.     else p_poly = p_edge -> poly[0];
  358.     p_next_edge = NULL;          /* In case of error, remains NULL. */
  359.     for (i=0; i<3; i++)              /* Test the 3 edges of the polygon: */
  360.         if (p_poly -> edge[i] != p_edge)
  361.             if (p_poly -> edge[i] -> status == ACTIVE)
  362.             p_next_edge = p_poly -> edge[i];
  363.     if (!p_next_edge) {
  364.         pc_tail -> next = NULL;
  365.         free_contour(p_cntr);
  366.         return NULL;
  367.     }
  368.     p_edge = p_next_edge;
  369.     PLastpoly = p_poly;
  370.     p_edge -> status = INACTIVE;
  371.     (*num_active)--;
  372.     pc_tail -> next = update_cntr_pt(p_edge, z_level, &in_middle);
  373.     if (!in_middle) {
  374.         pc_tail -> next = NULL;
  375.         free_contour(p_cntr);
  376.         return NULL;
  377.     }
  378.         pc_tail = pc_tail -> next;
  379.     }
  380.     while ((pe_start != p_edge) && (!p_edge -> boundary));
  381.     pc_tail -> next = NULL;
  382.  
  383.     return p_cntr;
  384. }
  385.  
  386. /*
  387.  * Allocates one contour location and update it to to correct position
  388.  * according to z_level and edge p_edge. if z_level is found to be at
  389.  * one of the extreme points nothing is allocated (NULL is returned)
  390.  * and in_middle is set to FALSE.
  391.  */
  392. static struct cntr_struct *update_cntr_pt(p_edge, z_level, in_middle)
  393. struct edge_struct *p_edge;
  394. double z_level;
  395. int *in_middle;
  396. {
  397.     double t;
  398.     struct cntr_struct *p_cntr;
  399.  
  400.     t = (z_level - p_edge -> vertex[0] -> Z) /
  401.     (p_edge -> vertex[1] -> Z - p_edge -> vertex[0] -> Z);
  402.  
  403.     if (fuzzy_equal(t, 1.0) || fuzzy_equal(t, 0.0)) {
  404.         *in_middle = FALSE;
  405.         return NULL;
  406.     }
  407.     else {
  408.     *in_middle = TRUE;
  409.     p_cntr = (struct cntr_struct *) alloc(sizeof(struct cntr_struct),
  410.                             "contour cntr_struct");
  411.     p_cntr -> X = p_edge -> vertex[1] -> X * t +
  412.              p_edge -> vertex[0] -> X * (1-t);
  413.     p_cntr -> Y = p_edge -> vertex[1] -> Y * t +
  414.              p_edge -> vertex[0] -> Y * (1-t);
  415.     return p_cntr;
  416.     }
  417. }
  418.  
  419. /*
  420.  * Simple routine to decide if two real values are equal by simply
  421.  * calculating the relative/absolute error between them (< EPSILON).
  422.  */
  423. static int fuzzy_equal(x, y)
  424. double x, y;
  425. {
  426.     if (abs(x) > EPSILON)            /* Calculate relative error: */
  427.         return (abs((x - y) / x) < EPSILON);
  428.     else                    /* Calculate absolute error: */
  429.     return (abs(x - y) < EPSILON);
  430. }
  431.  
  432. /*
  433.  * Generate the triangles.
  434.  * Returns the lists (vrtxs edges & polys) via pointers to their heads.
  435.  */
  436. static void gen_triangle(num_isolines, iso_lines, p_polys, p_edges,
  437.     p_vrts, x_min, y_min, z_min, x_max, y_max, z_max)
  438. int num_isolines;
  439. struct iso_curve *iso_lines;
  440. struct poly_struct **p_polys;
  441. struct edge_struct **p_edges;
  442. struct vrtx_struct **p_vrts;
  443. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  444. {
  445.     int i, grid_x_max = iso_lines->p_count;
  446.     struct vrtx_struct *p_vrtx1, *p_vrtx2, *pv_temp;
  447.     struct edge_struct *p_edge1, *p_edge2, *pe_tail1, *pe_tail2, *pe_temp,
  448.               *p_edge_middle, *pe_m_tail;
  449.     struct poly_struct *p_poly, *pp_tail;
  450.  
  451.     *p_polys = NULL;
  452.     *p_edges = NULL;
  453.     *p_vrts = NULL;
  454.     *z_min = INFINITY;
  455.     *y_min = INFINITY;
  456.     *x_min = INFINITY;
  457.     *z_max = -INFINITY;
  458.     *y_max = -INFINITY;
  459.     *x_max = -INFINITY;
  460.  
  461.     /* Read 1st row. */
  462.     p_vrtx1 = gen_vertices(grid_x_max, iso_lines->points,
  463.                x_min, y_min, z_min, x_max, y_max, z_max);
  464.     *p_vrts = p_vrtx1;
  465.     /* Gen. its edges.*/
  466.     pe_temp = p_edge1 = gen_edges(grid_x_max, p_vrtx1, &pe_tail1);
  467.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  468.     pe_temp -> poly[1] = NULL;
  469.     pe_temp = pe_temp -> next;
  470.     }
  471.     for (i = 1; i < num_isolines; i++) { /* Read next column and gen. polys. */
  472.     iso_lines = iso_lines->next;
  473.         /* Get row into list. */
  474.         p_vrtx2 = gen_vertices(grid_x_max, iso_lines->points,
  475.                    x_min, y_min, z_min, x_max, y_max, z_max);
  476.         /* Generate its edges. */
  477.         p_edge2 = gen_edges(grid_x_max, p_vrtx2, &pe_tail2);
  478.     /* Generate edges from one vertex list to the other one: */
  479.     p_edge_middle = gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  480.                                  &pe_m_tail);
  481.  
  482.     /* Now we can generate the polygons themselves (triangles). */
  483.     p_poly = gen_polys(grid_x_max, p_edge1, p_edge_middle, p_edge2,
  484.                                  &pp_tail);
  485.         pe_tail1 -> next = (*p_edges);      /* Chain new edges to main list. */
  486.         pe_m_tail -> next = p_edge1;
  487.     *p_edges = p_edge_middle;
  488.     pe_tail1 = pe_tail2;
  489.     p_edge1 = p_edge2;
  490.  
  491.     pv_temp = p_vrtx2;
  492.     while (pv_temp -> next) pv_temp = pv_temp -> next;
  493.     pv_temp -> next = *p_vrts;
  494.     *p_vrts = p_vrtx1 = p_vrtx2;
  495.  
  496.         pp_tail -> next = (*p_polys);       /* Chain new polys to main list. */
  497.     *p_polys = p_poly;
  498.     }
  499.  
  500.     pe_temp = p_edge1;
  501.     for (i = 1; i < grid_x_max; i++) {/* Mark one side of edges as boundary. */
  502.     pe_temp -> poly[0] = NULL;
  503.     pe_temp = pe_temp -> next;
  504.     }
  505.  
  506.     pe_tail1 -> next = (*p_edges);    /* Chain last edges list to main list. */
  507.     *p_edges = p_edge1;
  508.  
  509.     /* Update the boundary flag, saved in each edge, and update indexes: */
  510.     pe_temp = (*p_edges);
  511.     i = 1;
  512.  
  513.     while (pe_temp) {
  514.     pe_temp -> boundary = (!(pe_temp -> poly[0])) ||
  515.                   (!(pe_temp -> poly[1]));
  516.     pe_temp = pe_temp -> next;
  517.     }
  518. }
  519.  
  520. /*
  521.  * Handles grid_x_max 3D points (One row) and generate linked list for them.
  522.  */
  523. static struct vrtx_struct *gen_vertices(grid_x_max, points,
  524.                       x_min, y_min, z_min, x_max, y_max, z_max)
  525. int grid_x_max;
  526. struct coordinate *points;
  527. double *x_min, *y_min, *z_min, *x_max, *y_max, *z_max;
  528. {
  529.     int i;
  530.     struct vrtx_struct *p_vrtx, *pv_tail, *pv_temp;
  531.  
  532.     for (i=0; i<grid_x_max; i++) {/* Get a point and generate the structure. */
  533.         pv_temp = (struct vrtx_struct *) alloc(sizeof(struct vrtx_struct),
  534.                         "contour vertex");
  535.     pv_temp -> X = points[i].x;
  536.     pv_temp -> Y = points[i].y;
  537.     pv_temp -> Z = points[i].z;
  538.  
  539.     if (pv_temp -> X > *x_max) *x_max = pv_temp -> X; /* Update min/max. */
  540.     if (pv_temp -> Y > *y_max) *y_max = pv_temp -> Y;
  541.     if (pv_temp -> Z > *z_max) *z_max = pv_temp -> Z;
  542.     if (pv_temp -> X < *x_min) *x_min = pv_temp -> X;
  543.     if (pv_temp -> Y < *y_min) *y_min = pv_temp -> Y;
  544.     if (pv_temp -> Z < *z_min) *z_min = pv_temp -> Z;
  545.  
  546.     if (i == 0)                              /* First vertex in row: */
  547.         p_vrtx = pv_tail = pv_temp;
  548.     else {
  549.         pv_tail -> next = pv_temp;   /* Stick new record as last one. */
  550.         pv_tail = pv_tail -> next;    /* And continue to last record. */
  551.     }
  552.     }
  553.     pv_tail -> next = NULL;
  554.  
  555.     return p_vrtx;
  556. }
  557.  
  558. /*
  559.  * Combines N vertices in pair to form N-1 edges.
  560.  * Returns pointer to the edge list (pe_tail will point on last edge in list).
  561.  */
  562. static struct edge_struct *gen_edges(grid_x_max, p_vrtx, pe_tail)
  563. int grid_x_max;
  564. struct vrtx_struct *p_vrtx;
  565. struct edge_struct **pe_tail;
  566. {
  567.     int i;
  568.     struct edge_struct *p_edge, *pe_temp;
  569.  
  570.     for (i=0; i<grid_x_max-1; i++) {         /* Generate grid_x_max-1 edges: */
  571.     pe_temp = (struct edge_struct *) alloc(sizeof(struct edge_struct),
  572.                         "contour edge");
  573.     pe_temp -> vertex[0] = p_vrtx;              /* First vertex of edge. */
  574.     p_vrtx = p_vrtx -> next;                     /* Skip to next vertex. */
  575.     pe_temp -> vertex[1] = p_vrtx;             /* Second vertex of edge. */
  576.         if (i == 0)                                    /* First edge in row: */
  577.         p_edge = (*pe_tail) = pe_temp;
  578.     else {
  579.         (*pe_tail) -> next = pe_temp;   /* Stick new record as last one. */
  580.         *pe_tail = (*pe_tail) -> next;   /* And continue to last record. */
  581.      }
  582.     }
  583.     (*pe_tail) -> next = NULL;
  584.  
  585.     return p_edge;
  586. }
  587.  
  588. /*
  589.  * Combines 2 lists of N vertices each into edge list:
  590.  * The dots (.) are the vertices list, and the              .  .  .  .
  591.  *  edges generated are alternations of vertical edges      |\ |\ |\ |
  592.  *  (|) and diagonal ones (\).                              | \| \| \|
  593.  *  A pointer to edge list (alternate | , \) is returned    .  .  .  .
  594.  * Note this list will have (2*grid_x_max-1) edges (pe_tail points on last
  595.  * record).
  596.  */
  597. static struct edge_struct *gen_edges_middle(grid_x_max, p_vrtx1, p_vrtx2,
  598.                                 pe_tail)
  599. int grid_x_max;
  600. struct vrtx_struct *p_vrtx1, *p_vrtx2;
  601. struct edge_struct **pe_tail;
  602. {
  603.     int i;
  604.     struct edge_struct *p_edge, *pe_temp;
  605.  
  606.     /* Gen first (|). */
  607.     pe_temp = (struct edge_struct *) alloc(sizeof(struct edge_struct),
  608.                             "contour edge");
  609.     pe_temp -> vertex[0] = p_vrtx2;                 /* First vertex of edge. */
  610.     pe_temp -> vertex[1] = p_vrtx1;                /* Second vertex of edge. */
  611.     p_edge = (*pe_tail) = pe_temp;
  612.  
  613.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 edges /| for each.*/
  614.     for (i=0; i<grid_x_max-1; i++) {
  615.     /* The / edge. */
  616.     pe_temp = (struct edge_struct *) alloc(sizeof(struct edge_struct),
  617.                             "contour edge");
  618.     pe_temp -> vertex[0] = p_vrtx1;             /* First vertex of edge. */
  619.     pe_temp -> vertex[1] = p_vrtx2 -> next;    /* Second vertex of edge. */
  620.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  621.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  622.  
  623.     /* The | edge. */
  624.     pe_temp = (struct edge_struct *) alloc(sizeof(struct edge_struct),
  625.                             "contour edge");
  626.     pe_temp -> vertex[0] = p_vrtx2 -> next;     /* First vertex of edge. */
  627.     pe_temp -> vertex[1] = p_vrtx1 -> next;    /* Second vertex of edge. */
  628.         (*pe_tail) -> next = pe_temp;       /* Stick new record as last one. */
  629.     *pe_tail = (*pe_tail) -> next;       /* And continue to last record. */
  630.  
  631.         p_vrtx1 = p_vrtx1 -> next;   /* Skip to next vertices in both lists. */
  632.         p_vrtx2 = p_vrtx2 -> next;
  633.     }
  634.     (*pe_tail) -> next = NULL;
  635.  
  636.     return p_edge;
  637. }
  638.  
  639. /*
  640.  * Combines 3 lists of edges into triangles:
  641.  * 1. p_edge1: Top horizontal edge list:        -----------------------
  642.  * 2. p_edge_middge: middle edge list:         |\  |\  |\  |\  |\  |\  |
  643.  *                                             |  \|  \|  \|  \|  \|  \|
  644.  * 3. p_edge2: Bottom horizontal edge list:     -----------------------
  645.  * Note that p_edge1/2 lists has grid_x_max-1 edges, while p_edge_middle has
  646.  * (2*grid_x_max-1) edges.
  647.  * The routine simple scans the two list    Upper 1         Lower
  648.  * and generate two triangle upper one        ----         | \
  649.  * and lower one from the lists:             0\   |2      0|   \1
  650.  * (Nums. are edges order in polys)             \ |         ----
  651.  * The routine returns a pointer to a                         2
  652.  * polygon list (pp_tail points on last polygon).          1
  653.  *                                                   -----------
  654.  * In addition, the edge lists are updated -        | \   0     |
  655.  * each edge has two pointers on the two            |   \       |
  656.  * (one active if boundary) polygons which         0|1   0\1   0|1
  657.  * uses it. These two pointer to polygons           |       \   |
  658.  * are named: poly[0], poly[1]. The diagram         |    1    \ |
  659.  * on the right show how they are used for the       -----------
  660.  * upper and lower polygons.                             0
  661.  */
  662. static struct poly_struct *gen_polys(grid_x_max, p_edge1, p_edge_middle,
  663.                             p_edge2, pp_tail)
  664. int grid_x_max;
  665. struct edge_struct *p_edge1, *p_edge_middle, *p_edge2;
  666. struct poly_struct **pp_tail;
  667. {
  668.     int i;
  669.     struct poly_struct *p_poly, *pp_temp;
  670.  
  671.     p_edge_middle -> poly[0] = NULL;                /* Its boundary! */
  672.  
  673.     /* Advance in vrtx list grid_x_max-1 times, and gen. 2 polys for each. */
  674.     for (i=0; i<grid_x_max-1; i++) {
  675.     /* The Upper. */
  676.     pp_temp = (struct poly_struct *) alloc(sizeof(struct poly_struct),
  677.                             "contour poly");
  678.     /* Now update polys about its edges, and edges about the polygon. */
  679.     pp_temp -> edge[0] = p_edge_middle -> next;
  680.     p_edge_middle -> next -> poly[1] = pp_temp;
  681.     pp_temp -> edge[1] = p_edge1;
  682.     p_edge1 -> poly[0] = pp_temp;
  683.     pp_temp -> edge[2] = p_edge_middle -> next -> next;
  684.     p_edge_middle -> next -> next -> poly[0] = pp_temp;
  685.     if (i == 0)                   /* Its first one in list: */
  686.         p_poly = (*pp_tail) = pp_temp;
  687.     else {
  688.         (*pp_tail) -> next = pp_temp;
  689.         *pp_tail = (*pp_tail) -> next;
  690.     }
  691.  
  692.     /* The Lower. */
  693.     pp_temp = (struct poly_struct *) alloc(sizeof(struct poly_struct),
  694.                             "contour poly");
  695.     /* Now update polys about its edges, and edges about the polygon. */
  696.     pp_temp -> edge[0] = p_edge_middle;
  697.     p_edge_middle -> poly[1] = pp_temp;
  698.     pp_temp -> edge[1] = p_edge_middle -> next;
  699.     p_edge_middle -> next -> poly[0] = pp_temp;
  700.     pp_temp -> edge[2] = p_edge2;
  701.     p_edge2 -> poly[1] = pp_temp;
  702.     (*pp_tail) -> next = pp_temp;
  703.     *pp_tail = (*pp_tail) -> next;
  704.  
  705.         p_edge1 = p_edge1 -> next;
  706.         p_edge2 = p_edge2 -> next;
  707.         p_edge_middle = p_edge_middle -> next -> next;
  708.     }
  709.     p_edge_middle -> poly[1] = NULL;                /* Its boundary! */
  710.     (*pp_tail) -> next = NULL;
  711.  
  712.     return p_poly;
  713. }
  714.  
  715. /*
  716.  * Calls the (hopefully) desired interpolation/approximation routine.
  717.  */
  718. static void put_contour(p_cntr, z_level, x_min, x_max, y_min, y_max, contr_kind)
  719. struct cntr_struct *p_cntr;
  720. double z_level, x_min, x_max, y_min, y_max;
  721. int contr_kind;
  722. {
  723.     if (!p_cntr) return;            /* Nothing to do if it is empty contour. */
  724.  
  725.     switch (interp_kind) {
  726.     case INTERP_NOTHING:              /* No interpolation/approximation. */
  727.         put_contour_nothing(p_cntr);
  728.         break;
  729.     case INTERP_CUBIC:                    /* Cubic spline interpolation. */
  730.         put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  731.                                 contr_kind);
  732.         break;
  733.     case APPROX_BSPLINE:                       /* Bspline approximation. */
  734.         put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  735.                                     contr_kind);
  736.         break;
  737.     }
  738.  
  739.     free_contour(p_cntr);
  740. }
  741.  
  742. /*
  743.  * Simply puts contour coordinates in order with no interpolation or
  744.  * approximation.
  745.  */
  746. static put_contour_nothing(p_cntr)
  747. struct cntr_struct *p_cntr;
  748. {
  749.     while (p_cntr) {
  750.     add_cntr_point(p_cntr -> X, p_cntr -> Y);
  751.     p_cntr = p_cntr -> next;
  752.     }
  753.     end_crnt_cntr();
  754. }
  755.  
  756. /*
  757.  * Find Complete Cubic Spline Interpolation.
  758.  */
  759. static put_contour_cubic(p_cntr, z_level, x_min, x_max, y_min, y_max,
  760.                                  contr_kind)
  761. struct cntr_struct *p_cntr;
  762. double z_level, x_min, x_max, y_min, y_max;
  763. int contr_kind;
  764. {
  765.     int num_pts, i;
  766.     double tx1, ty1, tx2, ty2;                    /* Tangents at end points. */
  767.     struct cntr_struct *pc_temp;
  768.  
  769.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  770.  
  771.     if (num_pts > 2) {  /* Take into account 3 points in tangent estimation. */
  772.     calc_tangent(3, p_cntr -> X, p_cntr -> next -> X,
  773.             p_cntr -> next -> next -> X,
  774.             p_cntr -> Y, p_cntr -> next -> Y,
  775.             p_cntr -> next -> next -> Y, &tx1, &ty1);
  776.     pc_temp = p_cntr;
  777.     for (i=3; i<num_pts; i++) pc_temp = pc_temp -> next;/* Go to the end.*/
  778.     calc_tangent(3, pc_temp -> next -> next -> X,
  779.              pc_temp -> next -> X, pc_temp -> X,
  780.             pc_temp -> next -> next -> Y,
  781.             pc_temp -> next -> Y, pc_temp -> Y, &tx2, &ty2);
  782.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  783.         ty2 = (-ty2);
  784.     }
  785.     /* If following (num_pts > 1) is TRUE then exactly 2 points in contour.  */
  786.     else if (num_pts > 1) {/* Take into account 2 points in tangent estimat. */
  787.     calc_tangent(2, p_cntr -> X, p_cntr -> next -> X, 0.0,
  788.             p_cntr -> Y, p_cntr -> next -> Y, 0.0, &tx1, &ty1);
  789.     calc_tangent(2, p_cntr -> next -> X, p_cntr -> X, 0.0,
  790.             p_cntr -> next -> Y, p_cntr -> Y, 0.0, &tx2, &ty2);
  791.         tx2 = (-tx2);   /* Inverse the vector as we need opposite direction. */
  792.         ty2 = (-ty2);
  793.     }
  794.     else return;            /* Only one point (???) - ignore it. */
  795.  
  796.     switch (contr_kind) {
  797.     case OPEN_CONTOUR:
  798.         break;
  799.     case CLOSED_CONTOUR:
  800.         tx1 = tx2 = (tx1 + tx2) / 2.0;         /* Make tangents equal. */
  801.         ty1 = ty2 = (ty1 + ty2) / 2.0;
  802.         break;
  803.     }
  804.     complete_spline_interp(p_cntr, num_pts, 0.0, 1.0, tx1, ty1, tx2, ty2);
  805.     end_crnt_cntr();
  806. }
  807.  
  808. /*
  809.  * Find Bspline approximation for this data set.
  810.  * Uses global variable num_approx_pts to determine number of samples per
  811.  * interval, where the knot vector intervals are assumed to be uniform, and
  812.  * Global variable bspline_order for the order of Bspline to use.
  813.  */
  814. static put_contour_bspline(p_cntr, z_level, x_min, x_max, y_min, y_max,
  815.                                 contr_kind)
  816. struct cntr_struct *p_cntr;
  817. double z_level, x_min, x_max,  y_min, y_max;
  818. int contr_kind;
  819. {
  820.     int num_pts, i, order = bspline_order;
  821.     struct cntr_struct *pc_temp;
  822.  
  823.     num_pts = count_contour(p_cntr);         /* Number of points in contour. */
  824.     if (num_pts < 2) return;     /* Cannt do nothing if empty or one points! */
  825.     /* Order must be less than number of points in curve - fix it if needed. */
  826.     if (order > num_pts - 1) order = num_pts - 1;
  827.  
  828.     gen_bspline_approx(p_cntr, num_pts, order, contr_kind);
  829.     end_crnt_cntr();
  830. }
  831.  
  832. /*
  833.  * Estimate the tangents according to the n last points where n might be
  834.  * 2 or 3 (if 2 onlt x1, x2).
  835.  */
  836. static calc_tangent(n, x1, x2, x3, y1, y2, y3, tx, ty)
  837. int n;
  838. double x1, x2, x3, y1, y2, y3, *tx, *ty;
  839. {
  840.     double v1[2], v2[2], v1_magnitude, v2_magnitude;
  841.  
  842.     switch (n) {
  843.     case 2:
  844.         *tx = (x2 - x1) * 0.3;
  845.         *ty = (y2 - y1) * 0.3;
  846.         break;
  847.     case 3:
  848.         v1[0] = x2 - x1;   v1[1] = y2 - y1;
  849.         v2[0] = x3 - x2;   v2[1] = y3 - y2;
  850.         v1_magnitude = sqrt(sqr(v1[0]) + sqr(v1[1]));
  851.         v2_magnitude = sqrt(sqr(v2[0]) + sqr(v2[1]));
  852.         *tx = (v1[0] / v1_magnitude) - (v2[0] / v2_magnitude) * 0.1;
  853.         *tx *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  854.         *ty = (v1[1] / v1_magnitude) - (v2[1] / v2_magnitude) * 0.1;
  855.         *ty *= v1_magnitude * 0.1;  /* Make tangent less than magnitude. */
  856.         break;
  857.     default:                       /* Should not happen! */
  858.         (*ty) = 0.1;
  859.         *tx = 0.1;
  860.         break;
  861.     }
  862. }
  863.  
  864. /*
  865.  * Free all elements in the contour list.
  866.  */
  867. static void free_contour(p_cntr)
  868. struct cntr_struct *p_cntr;
  869. {
  870.     struct cntr_struct *pc_temp;
  871.  
  872.     while (p_cntr) {
  873.     pc_temp = p_cntr;
  874.     p_cntr = p_cntr -> next;
  875.     free((char *) pc_temp);
  876.     }
  877. }
  878.  
  879. /*
  880.  * Counts number of points in contour.
  881.  */
  882. static int count_contour(p_cntr)
  883. struct cntr_struct *p_cntr;
  884. {
  885.     int count = 0;
  886.  
  887.     while (p_cntr) {
  888.     count++;
  889.     p_cntr = p_cntr -> next;
  890.     }
  891.     return count;
  892. }
  893.  
  894. /*
  895.  * Interpolate given point list (defined via p_cntr) using Complete
  896.  * Spline interpolation.
  897.  */
  898. static complete_spline_interp(p_cntr, n, t_min, t_max, tx1, ty1, tx2, ty2)
  899. struct cntr_struct *p_cntr;
  900. int n;
  901. double t_min, t_max, tx1, ty1, tx2, ty2;
  902. {
  903.     double dt, *tangents_x, *tangents_y;
  904.     int i;
  905.  
  906.     tangents_x = (double *) alloc((unsigned) (sizeof(double) * n),
  907.                         "contour c_s_intr");
  908.     tangents_y = (double *) alloc((unsigned) (sizeof(double) * n),
  909.                         "contour c_s_intr");
  910.  
  911.     if (n > 1) prepare_spline_interp(tangents_x, tangents_y, p_cntr, n,
  912.                     t_min, t_max, tx1, ty1, tx2, ty2);
  913.     else {
  914.     free((char *) tangents_x);
  915.     free((char *) tangents_y);
  916.     return;
  917.     }
  918.  
  919.     dt = (t_max-t_min)/(n-1);
  920.  
  921.     add_cntr_point(p_cntr -> X, p_cntr -> Y);           /* First point. */
  922.  
  923.     for (i=0; i<n-1; i++) {
  924.         hermit_interp(p_cntr -> X, p_cntr -> Y,
  925.                      tangents_x[i], tangents_y[i],
  926.              p_cntr -> next -> X, p_cntr -> next -> Y,
  927.                      tangents_x[i+1], tangents_y[i+1], dt);
  928.  
  929.         p_cntr = p_cntr -> next;
  930.     }
  931.  
  932.     free((char *) tangents_x);
  933.     free((char *) tangents_y);
  934. }
  935.  
  936. /*
  937.  * Routine to calculate intermidiate value of the Hermit Blending function:
  938.  * This routine should be called only ONCE at the beginning of the program.
  939.  */
  940. static calc_hermit_table()
  941. {
  942.     int i;
  943.     double t, dt;
  944.  
  945.     hermit_table = (table_entry *) alloc ((unsigned) (sizeof(table_entry) *
  946.                         (num_approx_pts + 1)),
  947.                         "contour hermit table");
  948.     t = 0;
  949.     dt = 1.0/num_approx_pts;
  950.     for (i=0; i<=num_approx_pts; i++) {
  951.         hermit_table[i][0] = (t-1)*(t-1)*(2*t+1);             /* h00. */
  952.         hermit_table[i][1] = t*t*(-2*t+3);                 /* h10. */
  953.         hermit_table[i][2] = t*(t-1)*(t-1);                 /* h01. */
  954.         hermit_table[i][3] = t*t*(t-1);                     /* h11. */
  955.         t = t + dt;
  956.     }
  957. }
  958.  
  959. /*
  960.  * Routine to generate an hermit interpolation between two points given as
  961.  * two InterpStruct structures. Assume hermit_table is already calculated.
  962.  * Currently the points generated are printed to stdout as two reals (X, Y).
  963.  */
  964. static hermit_interp(x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt)
  965. double x1, y1, tx1, ty1, x2, y2, tx2, ty2, dt;
  966. {
  967.     int i;
  968.     double x, y, vec_size, tang_size;
  969.  
  970.     tx1 *= dt;  ty1 *= dt; /* Normalize the tangents according to param. t.  */
  971.     tx2 *= dt;  ty2 *= dt;
  972.  
  973.     /* Normalize the tangents so that their magnitude will be 1/3 of the     */
  974.     /* segment length. This tumb rule guaranteed no cusps or loops!          */
  975.     /* Note that this normalization keeps continuity to be G1 (but not C1).  */
  976.     vec_size = sqrt(sqr(x1 - x2) + sqr(y2 - y1));
  977.     tang_size = sqrt(sqr(tx1) + sqr(ty1));                  /* Normalize T1. */
  978.     if (tang_size * 3 > vec_size) {
  979.     tx1 *= vec_size / (tang_size * 3);
  980.     ty1 *= vec_size / (tang_size * 3);
  981.     }
  982.     tang_size = sqrt(sqr(tx2) + sqr(ty2));                  /* Normalize T2. */
  983.     if (tang_size * 3 > vec_size) {
  984.     tx2 *= vec_size / (tang_size * 3);
  985.     ty2 *= vec_size / (tang_size * 3);
  986.     }
  987.  
  988.     for (i=1; i<=num_approx_pts; i++) {      /* Note we start from 1 - first */
  989.         x = hermit_table[i][0] * x1 +       /* point is not printed as it is */
  990.             hermit_table[i][1] * x2 +   /* redundent (last on last section). */
  991.             hermit_table[i][2] * tx1 +
  992.             hermit_table[i][3] * tx2;
  993.         y = hermit_table[i][0] * y1 +
  994.             hermit_table[i][1] * y2 +
  995.             hermit_table[i][2] * ty1 +
  996.             hermit_table[i][3] * ty2;
  997.     add_cntr_point(x, y);
  998.     }
  999. }
  1000.  
  1001. /*
  1002.  * Routine to Set up the 3*N mat for solve_tri_diag routine used in the
  1003.  * Complete Spline Interpolation. Returns TRUE of calc O.K.
  1004.  * Gets the points list in p_cntr (Of length n) and with tangent vectors tx1,
  1005.  * ty1 at starting point and tx2, ty2 and end point.
  1006.  */
  1007. static prepare_spline_interp(tangents_x, tangents_y, p_cntr, n, t_min, t_max,
  1008.                tx1, ty1, tx2, ty2)
  1009. double tangents_x[], tangents_y[];
  1010. struct cntr_struct *p_cntr;
  1011. int n;
  1012. double t_min, t_max, tx1, ty1, tx2, ty2;
  1013. {
  1014.     int i;
  1015.     double *r, t, dt;
  1016.     tri_diag *m;           /* The tri-diagonal matrix is saved here. */
  1017.     struct cntr_struct *p;
  1018.  
  1019.     m = (tri_diag *) alloc((unsigned) (sizeof(tri_diag) * n),
  1020.                         "contour tri_diag");
  1021.     r = (double *) alloc((unsigned) (sizeof(double) * n),
  1022.                         "contour tri_diag2");
  1023.     n--;
  1024.  
  1025.     p = p_cntr;
  1026.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1027.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1028.     r[0] = tx1;                           /* Set start tangent. */
  1029.     r[n] = tx2;                         /* Set end tangent. */
  1030.     t = t_min;
  1031.     dt = (t_max-t_min)/n;
  1032.     for (i=1; i<n; i++) {
  1033.        t = t + dt;
  1034.        m[i][0] = dt;
  1035.        m[i][2] = dt;
  1036.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1037.        r[i] = m[i][0] * ((p -> next -> X) - (p -> X)) / m[i][2]
  1038.             + m[i][2] * ((p -> next -> next -> X) - 
  1039.                          (p -> next -> X)) / m[i][0];
  1040.        r[i] *= 3.0;
  1041.        p = p -> next;
  1042.     }
  1043.  
  1044.     if (!solve_tri_diag(m, r, tangents_x, n+1)) { /* Find the X(t) tangents. */
  1045.         free((char *) m);
  1046.         free((char *) r);
  1047.     int_error("Cannt interpolate X using complete splines", NO_CARET);
  1048.     }
  1049.  
  1050.     p = p_cntr;
  1051.     m[0][0] = 0.0;    m[0][1] = 1.0;    m[0][2] = 0.0;
  1052.     m[n][0] = 0.0;    m[n][1] = 1.0;    m[n][2] = 0.0;
  1053.     r[0] = ty1;                           /* Set start tangent. */
  1054.     r[n] = ty2;                         /* Set end tangent. */
  1055.     t = t_min;
  1056.     dt = (t_max-t_min)/n;
  1057.     for (i=1; i<n; i++) {
  1058.        t = t + dt;
  1059.        m[i][0] = dt;
  1060.        m[i][2] = dt;
  1061.        m[i][1] = 2 * (m[i][0] + m[i][2]);
  1062.        r[i] = m[i][0] * ((p -> next -> Y) - (p -> Y)) / m[i][2]
  1063.             + m[i][2] * ((p -> next -> next -> Y) -
  1064.                          (p -> next -> Y)) / m[i][0];
  1065.        r[i] *= 3.0;
  1066.        p = p -> next;
  1067.     }
  1068.  
  1069.     if (!solve_tri_diag(m, r, tangents_y, n+1)) { /* Find the Y(t) tangents. */
  1070.         free((char *) m);
  1071.         free((char *) r);
  1072.     int_error("Cannt interpolate Y using complete splines", NO_CARET);
  1073.     }
  1074.     free((char *) m);
  1075.     free((char *) r);
  1076. }
  1077.  
  1078. /*
  1079.  * Solve tri diagonal linear system equation. The tri diagonal matrix is
  1080.  * defined via matrix M, right side is r, and solution X i.e. M * X = R.
  1081.  * Size of system given in n. Return TRUE if solution exist.
  1082.  */
  1083. static int solve_tri_diag(m, r, x, n)
  1084. tri_diag m[];
  1085. double r[], x[];
  1086. int n;
  1087. {
  1088.     int i;
  1089.     double t;
  1090.  
  1091.     for (i=1; i<n; i++) {   /* Eliminate element m[i][i-1] (lower diagonal). */
  1092.     if (m[i-1][1] == 0) return FALSE;
  1093.     t = m[i][0] / m[i-1][1];        /* Find ratio between the two lines. */
  1094.     m[i][0] = m[i][0] - m[i-1][1] * t;
  1095.     m[i][1] = m[i][1] - m[i-1][2] * t;
  1096.     r[i] = r[i] - r[i-1] * t;
  1097.     }
  1098.     /* Now do back subtitution - update the solution vector X: */
  1099.     if (m[n-1][1] == 0) return FALSE;
  1100.     x[n-1] = r[n-1] / m[n-1][1];               /* Find last element. */
  1101.     for (i=n-2; i>=0; i--) {
  1102.     if (m[i][1] == 0) return FALSE;
  1103.     x[i] = (r[i] - x[i+1] * m[i][2]) / m[i][1];
  1104.     }
  1105.     return TRUE;
  1106. }
  1107.  
  1108. /*
  1109.  * Generate a Bspline curve defined by all the points given in linked list p:
  1110.  * Algorithm: using deBoor algorithm
  1111.  * Note: if Curvekind is OPEN_CONTOUR than Open end knot vector is assumed,
  1112.  *       else (CLOSED_CONTOUR) Float end knot vector is assumed.
  1113.  * It is assumed that num_of_points is at list 2, and order of Bspline is less
  1114.  * than num_of_points!
  1115.  */
  1116. static gen_bspline_approx(p_cntr, num_of_points, order, contour_kind)
  1117. struct cntr_struct *p_cntr;
  1118. int num_of_points, order, contour_kind;
  1119. {
  1120.     int i, knot_index = 0, pts_count = 1;
  1121.     double dt, t, next_t, t_min, t_max, x, y;
  1122.     struct cntr_struct *pc_temp = p_cntr, *pc_tail;
  1123.  
  1124.     /* If the contour is Closed one we must update few things:               */
  1125.     /* 1. Make the list temporary circular, so we can close the contour.     */
  1126.     /* 2. Update num_of_points - increase it by "order-1" so contour will be */
  1127.     /*    closed. This will evaluate order more sections to close it!        */
  1128.     if (contour_kind == CLOSED_CONTOUR) {
  1129.     pc_tail = p_cntr;
  1130.     while (pc_tail -> next) pc_tail = pc_tail -> next;/* Find last point.*/
  1131.     pc_tail -> next = p_cntr;   /* Close contour list - make it circular.*/
  1132.     num_of_points += order;
  1133.     }
  1134.  
  1135.     /* Find first (t_min) and last (t_max) t value to eval: */
  1136.     t = t_min = fetch_knot(contour_kind, num_of_points, order, order);
  1137.     t_max = fetch_knot(contour_kind, num_of_points, order, num_of_points);
  1138.     next_t = t_min + 1.0;
  1139.     knot_index = order;
  1140.     dt = 1.0/num_approx_pts;            /* Number of points per one section. */
  1141.  
  1142.  
  1143.     while (t<t_max) {
  1144.     if (t > next_t) {
  1145.         pc_temp = pc_temp -> next;     /* Next order ctrl. pt. to blend. */
  1146.             knot_index++;
  1147.         next_t += 1.0;
  1148.     }
  1149.         eval_bspline(t, pc_temp, num_of_points, order, knot_index,
  1150.                         contour_kind, &x, &y);   /* Next pt. */
  1151.     add_cntr_point(x, y);
  1152.     pts_count++;
  1153.     /* As we might have some real number round off problems we must      */
  1154.     /* test if we dont produce too many points here...                   */
  1155.     if (pts_count + 1 == num_approx_pts * (num_of_points - order) + 1)
  1156.             break;
  1157.         t += dt;
  1158.     }
  1159.  
  1160.     eval_bspline(t_max - EPSILON, pc_temp, num_of_points, order, knot_index,
  1161.         contour_kind, &x, &y);
  1162.     /* If from round off errors we need more than one last point: */
  1163.     for (i=pts_count; i<num_approx_pts * (num_of_points - order) + 1; i++)
  1164.     add_cntr_point(x, y);                /* Complete the contour. */
  1165.  
  1166.     if (contour_kind == CLOSED_CONTOUR)     /* Update list - un-circular it. */
  1167.     pc_tail -> next = NULL;
  1168. }
  1169.  
  1170. /*
  1171.  * The recursive routine to evaluate the B-spline value at point t using
  1172.  * knot vector PKList, and the control points Pdtemp. Returns x, y after the
  1173.  * division by the weight w. Note that Pdtemp points on the first control
  1174.  * point to blend with. The B-spline is of order order.
  1175.  */
  1176. static eval_bspline(t, p_cntr, num_of_points, order, j, contour_kind, x, y)
  1177. double t;
  1178. struct cntr_struct *p_cntr;
  1179. int num_of_points, order, j, contour_kind;
  1180. double *x, *y;
  1181. {
  1182.     int i, p;
  1183.     double ti, tikp, *dx, *dy;      /* Copy p_cntr into it to make it faster. */
  1184.  
  1185.     dx = (double *) alloc((unsigned) (sizeof(double) * (order + j)),
  1186.                         "contour b_spline");
  1187.     dy = (double *) alloc((unsigned) (sizeof(double) * (order + j)),
  1188.                         "contour b_spline");
  1189.     /* Set the dx/dy - [0] iteration step, control points (p==0 iterat.): */
  1190.     for (i=j-order; i<=j; i++) {
  1191.         dx[i] = p_cntr -> X;
  1192.         dy[i] = p_cntr -> Y;
  1193.         p_cntr = p_cntr -> next;
  1194.     }
  1195.  
  1196.     for (p=1; p<=order; p++) {        /* Iteration (b-spline level) counter. */
  1197.     for (i=j; i>=j-order+p; i--) {           /* Control points indexing. */
  1198.             ti = fetch_knot(contour_kind, num_of_points, order, i);
  1199.             tikp = fetch_knot(contour_kind, num_of_points, order, i+order+1-p);
  1200.         if (ti == tikp) {   /* Should not be a problems but how knows... */
  1201.         }
  1202.         else {
  1203.         dx[i] = dx[i] * (t - ti)/(tikp-ti) +         /* Calculate x. */
  1204.             dx[i-1] * (tikp-t)/(tikp-ti);
  1205.         dy[i] = dy[i] * (t - ti)/(tikp-ti) +         /* Calculate y. */
  1206.             dy[i-1] * (tikp-t)/(tikp-ti);
  1207.         }
  1208.     }
  1209.     }
  1210.     *x = dx[j]; *y = dy[j];
  1211.     free((char *) dx);
  1212.     free((char *) dy);
  1213. }
  1214.  
  1215. /*
  1216.  * Routine to get the i knot from uniform knot vector. The knot vector
  1217.  * might be float (Knot(i) = i) or open (where the first and last "order"
  1218.  * knots are equal). contour_kind determines knot kind - OPEN_CONTOUR means
  1219.  * open knot vector, and CLOSED_CONTOUR selects float knot vector.
  1220.  * Note the knot vector is not exist and this routine simulates it existance
  1221.  * Also note the indexes for the knot vector starts from 0.
  1222.  */
  1223. static double fetch_knot(contour_kind, num_of_points, order, i)
  1224. int contour_kind, num_of_points, order, i;
  1225. {
  1226.     switch (contour_kind) {
  1227.     case OPEN_CONTOUR:
  1228.         if (i <= order) return 0.0;
  1229.         else if (i <= num_of_points) return (double) (i - order);
  1230.          else return (double) (num_of_points - order);
  1231.     case CLOSED_CONTOUR:
  1232.         return (double) i;
  1233.     default: /* Should never happen */
  1234.         return 1.0;
  1235.     }
  1236. }
  1237.